<template>
  <div class="finance-edit-container">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h1>编辑财务记录</h1>
      <div class="action-buttons">
        <el-button @click="handleGoBack">
          <el-icon><ArrowLeft /></el-icon> 返回列表
        </el-button>
        <el-button type="primary" @click="handleSubmit">
          <el-icon><Check /></el-icon> 保存
        </el-button>
        <el-button @click="resetForm">
          <el-icon><Refresh /></el-icon> 重置
        </el-button>
      </div>
    </div>

    <!-- 表单卡片 -->
    <el-card class="form-card">
      <el-form
        ref="financeFormRef"
        :model="financeForm"
        :rules="formRules"
        label-width="120px"
        class="finance-form"
      >
        <!-- 基本信息区域 -->
        <div class="form-section">
          <h2 class="section-title">基本信息</h2>
          <el-divider></el-divider>
        </div>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="财务单号" prop="financeNo">
              <el-input v-model="financeForm.financeNo" disabled></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="交易类型" prop="type">
              <el-radio-group v-model="financeForm.type" disabled>
                <el-radio label="income">收入</el-radio>
                <el-radio label="expense">支出</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="关联订单号" prop="orderNo">
              <el-input v-model="financeForm.orderNo" disabled></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierName">
              <el-input v-model="financeForm.supplierName" disabled></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="交易日期" prop="transactionDate">
              <el-date-picker
                v-model="financeForm.transactionDate"
                type="date"
                placeholder="请选择交易日期"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="交易金额(元)" prop="amount">
              <el-input
                v-model.number="financeForm.amount"
                placeholder="请输入交易金额"
                :prefix-icon="financeForm.type === 'income' ? <CaretUp color='#67C23A' /> : <CaretDown color='#F56C6C' />"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="financeForm.paymentMethod" placeholder="请选择支付方式">
                <el-option label="银行转账" value="bankTransfer"></el-option>
                <el-option label="支付宝" value="alipay"></el-option>
                <el-option label="微信支付" value="wechat"></el-option>
                <el-option label="现金" value="cash"></el-option>
                <el-option label="其他" value="other"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 支付信息区域 -->
        <div class="form-section">
          <h2 class="section-title">支付信息</h2>
          <el-divider></el-divider>
        </div>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="银行名称" prop="bankName">
              <el-input v-model="financeForm.bankName" placeholder="请输入银行名称" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="银行账户" prop="bankAccount">
              <el-input v-model="financeForm.bankAccount" placeholder="请输入银行账户" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="交易流水号" prop="transactionNo">
              <el-input v-model="financeForm.transactionNo" placeholder="请输入交易流水号" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="支付时间" prop="paymentTime">
              <el-date-picker
                v-model="financeForm.paymentTime"
                type="datetime"
                placeholder="请选择支付时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 其他信息区域 -->
        <div class="form-section">
          <h2 class="section-title">其他信息</h2>
          <el-divider></el-divider>
        </div>

        <el-form-item label="备注信息" prop="remark">
          <el-input
            v-model="financeForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import {
  ArrowLeft,
  Check,
  Refresh,
  CaretUp,
  CaretDown
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';

// 路由实例
const router = useRouter();
const route = useRoute();

// 表单引用
const financeFormRef = ref<any>(null);

// 表单数据
const financeForm = reactive({
  id: '',
  financeNo: '',
  type: 'income',
  orderNo: '',
  supplierName: '',
  transactionDate: '',
  amount: 0,
  paymentMethod: '',
  bankName: '',
  bankAccount: '',
  transactionNo: '',
  paymentTime: '',
  remark: ''
});

// 表单验证规则
const formRules = reactive({
  transactionDate: [
    { required: true, message: '请选择交易日期', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入交易金额', trigger: 'blur' },
    { type: 'number', message: '交易金额必须为数字', trigger: 'blur' },
    { 
      validator: (rule: any, value: number, callback: any) => {
        if (value <= 0) {
          callback(new Error('交易金额必须大于0'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ],
  bankName: [
    { required: true, message: '请输入银行名称', trigger: 'blur' }
  ],
  bankAccount: [
    { required: true, message: '请输入银行账户', trigger: 'blur' }
  ]
});

// 返回列表
const handleGoBack = () => {
  router.push({ name: 'FinanceList' });
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await financeFormRef.value.validate();

    // 确认提交
    await ElMessageBox.confirm('确定要保存当前财务记录的修改吗？', '保存确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    });

    // 模拟API请求
    const loading = ElLoading.service({
      lock: true,
      text: '保存中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    setTimeout(() => {
      loading.close();
      ElMessage.success('财务记录更新成功');
      router.push({ name: 'FinanceDetail', params: { id: financeForm.id } });
    }, 1000);
  } catch (error) {
    // 表单验证失败或用户取消提交
    if (error !== 'cancel') {
      console.error('表单提交失败:', error);
    }
  }
};

// 重置表单
const resetForm = () => {
  getFinanceDetail();
};

// 获取财务记录详情
const getFinanceDetail = () => {
  // 显示加载中
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  // 模拟API请求
  setTimeout(() => {
    // 模拟数据
    const isIncome = Math.random() > 0.4;
    const amount = Math.floor(Math.random() * 100000) + 10000;
    const today = new Date();
    const transactionDate = new Date(today);
    transactionDate.setDate(today.getDate() - Math.floor(Math.random() * 10));

    // 设置表单数据
    Object.assign(financeForm, {
      id: route.params.id as string,
      financeNo: `FIN${Date.now()}`,
      orderNo: `ZCY${Date.now() - 10000}`,
      supplierName: `供应商${Math.floor(Math.random() * 1000) + 1}`,
      type: isIncome ? 'income' : 'expense',
      amount: isIncome ? amount : -amount,
      transactionDate: transactionDate.toISOString().slice(0, 10),
      paymentMethod: 'bankTransfer',
      bankName: '中国工商银行',
      bankAccount: '6222 **** **** 1234',
      transactionNo: `TR${Math.floor(Math.random() * 1000000000000)}`,
      paymentTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
      remark: '这是一条财务记录的详细备注信息，包含交易的具体说明和相关事项。'
    });

    // 关闭加载
    loading.close();
  }, 800);
};

// 页面加载时初始化
onMounted(() => {
  // 获取财务记录详情
  getFinanceDetail();
});
</script>

<style scoped lang="scss">
.finance-edit-container {
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.form-card {
  margin-bottom: 20px;
}

.finance-form {
  padding: 10px 0;
}

.form-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  margin-bottom: 10px;
  color: #303133;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .finance-edit-container {
    padding: 0 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .action-buttons {
    flex-wrap: wrap;
    width: 100%;
  }

  .el-col {
    &.lg-12 {
      flex: 0 0 100%;
      max-width: 100%;
    }
  }
}
</style>